<template>
  <div>
    <a-layout-content
      :style="{
        margin: '24px 16px',
        padding: '24px',
        background: '#fff',
        minHeight: '280px',
      }"
    >
      <a-form
        :form="form"
        :label-col="{ span: 5, offset: 5 }"
        :wrapper-col="{ span: 6 }"
        @submit="handleSubmit"
      >
        <a-form-item label="首页主图">
          <a-upload
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            action="http://localhost:8899/api/upload"
            :before-upload="beforeUpload"
            @change="handleChange"
          >
            <img
              v-if="imageUrl"
              :src="dataInfo.imgUrl"
              alt="avatar"
              style="width: 248px"
            />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="下单页详情图">
          <a-upload
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            action="http://localhost:8899/api/upload"
            :before-upload="beforeUpload2"
            @change="handleChange2"
          >
            <img
              v-if="imageUrl2"
              :src="dataInfo.detailsImgUrl"
              alt="avatar"
              style="width: 248px"
            />
            <div v-else>
              <a-icon :type="loading2 ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="产品名称">
          <a-textarea
            placeholder="输入产品名称"
            :auto-size="{ minRows: 2, maxRows: 5 }"
            v-model="dataInfo.title"
          />
        </a-form-item>
        <a-form-item label="单人开卡数量限制">
          <a-input-number
            id="inputNumber"
            v-model="dataInfo.maxPerson"
            :min="0"
            :max="99"
            placeholder="0为不限制"
          />
        </a-form-item>
        <a-form-item label="号卡归属地">
          <a-cascader
            :options="cityList.options"
            placeholder="选择号卡归属地"
            @change="onCascader"
          />
        </a-form-item>
        <a-form-item label="下单年龄限制">
          <a-input-group compact>
            <a-input
              style="width: 100px; text-align: center"
              placeholder="最小年龄"
              v-model="dataInfo.minAge"
            />
            <!-- maxLength="2" -->
            <a-input
              style="
                width: 30px;
                border-left: 0;
                pointer-events: none;
                backgroundcolor: #fff;
              "
              placeholder="~"
              disabled
            />
            <a-input
              style="width: 100px; text-align: center; border-left: 0"
              placeholder="最大年龄"
              v-model="dataInfo.maxAge"
            />
          </a-input-group>
        </a-form-item>

        <a-form-item label="运营商">
          <a-select
            placeholder="选择一个运营商"
            @change="handleSelectChange"
            :defaultValue="defaultOperator"
          >
           <!-- 完成到这了！！！默认选择 -->
            <a-select-option value="1"> 电信 </a-select-option>
            <a-select-option value="2"> 联通 </a-select-option>
            <a-select-option value="3"> 移动 </a-select-option>
            <a-select-option value="4"> 虚拟运营商 </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 6, offset: 10 }">
          <a-button type="primary" html-type="submit" :loading="uploading">
            添加产品
          </a-button>
        </a-form-item>
      </a-form>
    </a-layout-content>
  </div>
</template>
  
  <script>
import cityList from "@/api/cityCopy.js";
import { saveGood } from "@/api/index";
import { getGoodInfo } from "@/api/index";

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}
export default {
  name: "AddGood",
  components: { saveGood, getGoodInfo },
  data() {
    return {
      form: this.$form.createForm(this, { name: "coordinated" }),
      maxPerson: "", //单人限制
      minAge: "", //最小年龄
      maxAge: "", //最大年龄
      location: "", //归属地
      imgUrl: "", //首页主图
      detailsImgUrl: "", //详情页图片
      cityList,
      uploading: false,
      loading: false,
      imageUrl: "",
      loading2: false,
      imageUrl2: "",
      dataInfo:{},
      defaultOperator:''
    };
  },
  created() {
    if(this.$route.query.id){
      console.log(this.$route.query.id);
    setTimeout(() => {
      getGoodInfo(this.$route.query.id).then((res) => {
        console.log('res',res.data.data);
        this.dataInfo = res.data.data,
        this.imageUrl = res.data.data.imgUrl;
        this.imageUrl2 = res.data.data.detailsImgUrl;
        this.getOperatorText(res.data.data.operator)
      });
    }, 200);
    }

    
  },
  methods: {
    //地址选择事件
    onCascader(value) {
      this.location = value[0] + " " + value[1];
    },
    //提交按钮事件

    handleSubmit(e) {
      console.log(this.dataInfo.title);
      if(this.dataInfo.title == ''){
      this.$message.warning('产品名称不能为空')
    }
      console.log("data:", this.data);
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          // console.log(this.imgurl,this.detailsimgurl,values.title,this.maxperson,this.location,this.minage,this.maxage,values.operator);
          saveGood({
            imgurl: this.imgUrl,
            detailsimgurl: this.detailsImgUrl,
            title: values.title,
            maxperson: this.maxPerson,
            location: this.location,
            minage: this.minAge,
            maxage: this.maxAge,
            operator: values.operator,
          }).then((res) => {
            if (res.data.code != 200) {
              return this.$message.error("产品添加失败");
            }
            this.$message.success("产品添加成功");
            setTimeout(() => {
              this.$router.push("/admin/goodList");
            }, 800);
          });
        }
      });
    },
    handleSelectChange(value) {
      // console.log("选择了下拉框：", value);
      // this.form.setFieldsValue({
      //   note: `Hi, ${value === "male" ? "man" : "lady"}!`,
      // });
    },
    //↓上传文件
    handleChange(info) {
      if (info.file.status === "uploading") {
        this.loading = true;
        return;
      }
      if (info.file.status === "done") {
        // console.log('info:',info.fileList[0].response.data);
        this.imgurl = info.fileList[0].response.data;
        getBase64(info.file.originFileObj, (imageUrl) => {
          this.imageUrl = imageUrl;
          this.loading = false;
        });
      }
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.error("You can only upload JPG file!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("最大上传2MB!");
      }
      return isJpgOrPng && isLt2M;
    },
    handleChange2(info) {
      if (info.file.status === "uploading") {
        this.loading2 = true;
        return;
      }
      if (info.file.status === "done") {
        this.detailsimgurl = info.fileList[0].response.data;
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, (imageUrl) => {
          this.imageUrl2 = imageUrl;
          this.loading2 = false;
        });
      }
    },
    beforeUpload2(file) {
      const isJpgOrPng2 =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng2) {
        this.$message.error("You can only upload JPG file!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("最大上传2MB!");
      }
      return isJpgOrPng2 && isLt2M;
    },
    getOperatorText(code) {
      switch (code) {
        case 1:
          return this.defaultOperator="电信";
        case 2:
          return this.defaultOperator="联通";
        case 3:
          return this.defaultOperator="移动";
        case 4:
          return this.defaultOperator="虚拟";
        default:
          return this.defaultOperator="";
      }
    },
  },
};
</script>
  
  <style >
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>